package com.example.d4_homework.homework01;

import java.util.Arrays;
import java.util.Comparator;

public class Test {
    public static void main(String[] args) {
        // 创建存储学生对象的数组,并且将学生对象添加到数组中
        Student[] students = new Student[5];
        students[0] = new Student("郭靖", 175);
        students[1] = new Student("黄蓉", 155);
        students[2] = new Student("黄药师", 180);
        students[3] = new Student("欧阳锋", 170);
        students[4] = new Student("穆念慈", 160);

        // 调用sort方法排序
        // sort1(students);
        // 使用Lambda表达式简化
        // Arrays.sort(students, (o1, o2) -> o1.getHeight() - o2.getHeight());
        // 进一步简化
        Arrays.sort(students, Comparator.comparingInt(Student::getHeight));

        // 使用stream流,排序,输出,直接一行代码搞定
        // Arrays.stream(students).sorted(Comparator.comparingInt(Student::getHeight)).forEach(System.out::println);

        // 遍历集合
        for (int x = 0; x < students.length; x++) {
            System.out.println(students[x]);
        }
    }

    /**
     * 使用冒泡排序
     *
     * @param students 待排序的数组
     */
    public static void sort1(Student[] students) {
        for (int i = 0; i < students.length - 1; i++) {
            for (int j = 0; j < students.length - i - 1; j++) {
                if (students[j].getHeight() > students[j + 1].getHeight()) {
                    Student temp = students[j];
                    students[j] = students[j + 1];
                    students[j + 1] = temp;
                }
            }
        }
    }

    /**
     * 使用选择排序
     *
     * @param students 待排序的数组
     */
    public static void sort2(Student[] students) {
        for (int i = 0; i < students.length - 1; i++) {
            for (int j = i + 1; j < students.length; j++) {
                if (students[i].getHeight() > students[j].getHeight()) {
                    Student temp = students[i];
                    students[i] = students[j];
                    students[j] = temp;
                }
            }
        }
    }
}
